#include "attendance.h"
#include "ui_attendance.h"
#include <QDebug>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
#include <QSqlError>
#include <QSqlRecord>
#include <QMessageBox>
#include <QDateTime>

attendance::attendance(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::attendance)
{
    ui->setupUi(this);
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("43.141.197.129");  // 数据库主机
    db.setPort(29843);
    db.setDatabaseName("face"); // 数据库名
    db.setUserName("zheng");       // 数据库用户名
    db.setPassword("510823qizw@");   // 数据库密码
    if(!db.open())
    {
        qDebug()<<"MySQL数据库打开失败"<<db.lastError().text();
    }
    else
    {
        qDebug()<<"MySQL数据库连接成功";
    }
    // 设置表头标签之前先确保行列已设置
    ui->tb_widget->setRowCount(1);
    ui->tb_widget->setColumnCount(3); // 假设有6列
    // 设置水平方向的表头标签
    QStringList headerLabels;
    headerLabels << "reid"  << "empid"<< "checktime" ;
    ui->tb_widget->setHorizontalHeaderLabels(headerLabels);
    // 显示表头
    ui->tb_widget->horizontalHeader()->show();
    // 自动调整列宽
    ui->tb_widget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    // 或者也可以尝试调整列宽以适应内容
    ui->tb_widget->resizeColumnsToContents();
    qDebug()<<"support drivers:"<<QSqlDatabase::drivers();
    // 查询数据
    QSqlQuery query(db);
    bool queryOk = query.exec("SELECT reid, empid, checktime from attentance");
    if (!queryOk)
    {
        qDebug() << "Query failed: " << query.lastError().text();
        return;
    }
    // 获取查询结果的记录集
    QSqlRecord record = query.record();
    int row = 0;
    while (query.next())
    {
        // 插入新行
        ui->tb_widget->insertRow(row);
        // 遍历每一列，并将数据填入表格
        for (int col = 0; col < 3; ++col)
        {
            QString fieldName = record.fieldName(col);
            QTableWidgetItem *item = new QTableWidgetItem(query.value(fieldName).toString());
            ui->tb_widget->setItem(row, col, item);
        }
        ++row;
    }
    // 设置表格的行数
    ui->tb_widget->setRowCount(row);
    // 初始化服务器
    m_server = new QTcpServer(this);
    m_server->listen(QHostAddress::Any, 8888);
    connect(m_server, &QTcpServer::newConnection, this, &attendance::handleNewConnection);
}

attendance::~attendance()
{
    delete ui;
}

void attendance::on_le_search_textChanged(const QString &arg1)
{

    // 构造 SQL 查询条件字符串
    QString strcond = QString(
    "WHERE reid LIKE CONCAT('%%', :searchText, '%%') "
    "OR empid LIKE CONCAT('%%', :searchText, '%%') "
    "OR checktime LIKE CONCAT('%%', :searchText, '%%') "
    );
    //qDebug()<<"support drivers:"<<QSqlDatabase::drivers();
    QSqlQuery query;
    query.prepare(QString("SELECT reid, empid, checktime FROM attentance %1").arg(strcond));
    query.bindValue(":searchText", arg1);
    if (!query.exec()) {
    qDebug() << "Query failed:" << query.lastError().text();
    return;
    }
    // 清空表格
    ui->tb_widget->clearContents();
    ui->tb_widget->setRowCount(0);
    // 获取查询结果的记录集
    QSqlRecord record = query.record();
   int row = 0;
    while (query.next()) {
    // 插入新行
    ui->tb_widget->insertRow(row);
   // 遍历每一列，并将数据填入表格
    for (int col = 0; col < record.count(); ++col) {
    QString fieldName = record.fieldName(col);
    QTableWidgetItem *item = new QTableWidgetItem(query.value(fieldName).toString());
    ui->tb_widget->setItem(row, col, item);
    }
    ++row;
    }
   // 设置表格的行数
    ui->tb_widget->setRowCount(row);
}

void attendance::handleNewConnection()
{
    QTcpSocket *socket = m_server->nextPendingConnection();
    connect(socket, &QTcpSocket::readyRead, this, &attendance::handleReadyRead);
    connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
}

void attendance::handleReadyRead()
{
    // 从 TCP Socket 中读取数据
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(QObject::sender());
    if (socket) {
        QByteArray buffer = socket->readAll();
        QDataStream in(&buffer, QIODevice::ReadOnly);

        QString department, wid, name, time;

        in >> department >> wid >> name >> time;

        qDebug() << "Received department:" << department;
        qDebug() << "Received wid:" << wid;
        qDebug() << "Received name:" << name;
        qDebug() << "Received time:" << time;

        // 检查时间字符串是否为空
        if (time.isEmpty()) {
            qDebug() << "Time string is empty.";
            return;
        }

        // 将 QString 时间字符串解析为 QDateTime
        QDateTime dateTime = QDateTime::fromString(time, "yyyy-MM-dd hh:mm:ss");

        // 检查解析是否成功
        if (dateTime.isValid()) {
            QSqlQuery query;
            query.prepare("INSERT INTO attentance (reid, empid, checktime) VALUES (:reid, :wid, :time)");
            query.bindValue(":reid", 0); // 假设 reid 不需要具体值或可以为0
            query.bindValue(":wid", wid);
            query.bindValue(":time", dateTime); // 直接绑定 QDateTime 对象

            if (!query.exec()) {
                qDebug() << "Insertion failed:" << query.lastError().text();
            } else {
                qDebug() << "Data inserted successfully";

                // 更新表格视图
                int row = ui->tb_widget->rowCount();
                ui->tb_widget->insertRow(row);
                ui->tb_widget->setItem(row, 0, new QTableWidgetItem(department));
                ui->tb_widget->setItem(row, 1, new QTableWidgetItem(wid));
                ui->tb_widget->setItem(row, 2, new QTableWidgetItem(dateTime.toString("yyyy-MM-dd hh:mm:ss")));
            }
        } else {
            qDebug() << "Failed to parse time string:" << time;
            return;
        }
    } else {
        qDebug() << "Invalid sender";
    }
}
